package com.apesource.bookBuy.view;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;

import com.apesource.bookBuy.bean.Book;
import com.apesource.bookBuy.bean.PayBook;
import com.apesource.bookBuy.bean.User;
import com.apesource.bookBuy.conf.AlipayConfig;
import com.apesource.bookBuy.dao.DaoUtil;
import com.apesource.bookBuy.mapper.BookMapper;
import com.apesource.bookBuy.mapper.PayBookMapper;
import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import org.apache.ibatis.session.SqlSession;

@Path("alipay")
public class AliPayController extends Controller {
		
	private static final String Users = null;

	@ActionKey("/alipay")
	public void alipay() {
		//获得初始化的AlipayClient
		AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
		
		//设置请求参数
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		alipayRequest.setReturnUrl(AlipayConfig.return_url);
		alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
		
//		//商户订单号，商户网站订单系统中唯一订单号，必填
//		String out_trade_no = getPara("WIDout_trade_no");
//		//付款金额，必填
//		String total_amount = getPara("WIDtotal_amount");
//		//订单名称，必填
//		String subject = getPara("WIDsubject");
//		//商品描述，可空
//		String body = getPara("WIDbody");
		String randomCode=UUID.randomUUID().toString().substring(0,8);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String out_trade_no=sdf.format(new Date())+randomCode;
		SqlSession sqlSession= DaoUtil.getSqlSession();
		BookMapper bookMapper=sqlSession.getMapper(BookMapper.class);
		Book book=bookMapper.getBookById(getParaToInt("bookid"));
		DaoUtil.close(sqlSession);
		String total_amount= String.valueOf(book.getBookPrice());

		String subject="暮雪商购书信息";
		String body = book.getBookName();

		PayBook payBook=new PayBook();
		payBook.setBid(book.getBookId());
		payBook.setSubject(subject);
		payBook.setUid(((User)getSessionAttr("users")).getUid());
		payBook.setTradeno(out_trade_no);
		payBook.setTotal(book.getBookPrice());
		payBook.setBody(body);

		setSessionAttr("payBook", payBook);
		setSessionAttr("bookNum", book.getBookNum());

		
		// 请求阿里支付
		alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no  +"\"," 
				+ "\"total_amount\":\""+ total_amount  +"\"," 
				+ "\"subject\":\""+ subject  +"\"," 
				+ "\"body\":\""+ body  +"\"," 
				+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
		
			
			
		//请求
		String result = "";
		try {
			result = alipayClient.pageExecute(alipayRequest).getBody();
			
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		renderHtml(result);
		
	}

	@ActionKey("/aliretrun")
	public void alireturn() {
		//获取支付宝GET过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map<String,String[]> requestParams = getParaMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用
			try {
				valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			params.put(name, valueStr);
		}
		
		boolean signVerified = false;
		try {
			signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} //调用SDK验证签名
		//——请在这里编写您的程序（以下代码仅作参考）——
		if(signVerified) {
			PayBook payBook=(PayBook)getSessionAttr("payBook");
			SqlSession sqlSession= DaoUtil.getSqlSession();
			PayBookMapper payBookMapper=sqlSession.getMapper(PayBookMapper.class);
			BookMapper bookMapper=sqlSession.getMapper(BookMapper.class);
			int res=payBookMapper.addPayBook(payBook);
			if(res==1) {
				sqlSession.commit();
				render("/payOk.html");

				int res2=bookMapper.updateBookNum(payBook.getBid(),((int)getSessionAttr("bookNum"))-1);
				if(res2==1) {
					sqlSession.commit();
				}
				DaoUtil.close(sqlSession);




			}else render("/payFalse.html");
			
		}else {
			System.out.println("验签失败");
		}
	}

}
